package server;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author songyi
 * @date 2020/6/28 0028 14:54
 * @description 把请求信息进行封装（根据InputStream输入流封装）
 */
public class Request {

    private String host;
    // 请求方式(get/post)
    private String method;
    // url(/index,/index.html)
    private String url;
    // 其他属性从输入流解析出来
    private InputStream inputStream;

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public Request(InputStream inputStream) throws IOException {
        this.inputStream = inputStream;
        // 从输入流获取请求信息
        int count = 0;
        while (count == 0) {
            count = inputStream.available();
        }
        byte[] bytes = new byte[count];
        inputStream.read(bytes);
        String inputStr = new String(bytes);
        // 获取第一行请求头信息
        String firstLine = inputStr.split("\\n")[0]; // GET / HTTP/1.1
        String secondLine = inputStr.split("\\n")[1]; // Host: localhost:8080
        String[] firstLineStrings = firstLine.split(" ");
        String[] secondLineStrings = secondLine.split(": ");
        String[] split = secondLineStrings[1].split(":");
        this.host = split[0];
        this.method = firstLineStrings[0];
        this.url = firstLineStrings[1];
        System.out.println("请求 method: " + method);
        System.out.println("请求 url: " + url);
        System.out.println("请求 host: " + host);
    }

    public Request() {
    }
}
